package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext context;

    @GetMapping
    public Object listAll(){
        return regionService.listAll();
    }

    /**
     * 获取指定状态的地区
     */
    @GetMapping("/{state}")
    public Object selectByState(@PathVariable Integer state){
        return regionService.selectByState(state);
    }

    @GetMapping(value = "/{placeId}/strategies", produces = "text/html")
    public void selectStrategies(StrategyQuery qo, HttpServletResponse resp) throws Exception {
        //根据地区id查询攻略
        qo.setPageSize(4);
        PageInfo<Strategy> all = strategyService.query(qo);
        //根据地区和推荐查询攻略
        qo.setPageSize(0);
        qo.setState(Strategy.STATE_HOT);
        PageInfo<Strategy> hot = strategyService.query(qo);
        //将数据封装到一个map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("all",all);
        map.put("hot",hot);
        //创建freemarker的配置对象
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //指定模板路径
        configuration.setDirectoryForTemplateLoading(new File(context.getRealPath("template")));
        //找模板
        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate("strategyTemplate.ftl");
        //输出结果
        resp.setContentType("text/html;charset=utf-8");
        template.process(map,resp.getWriter());
    }

    @GetMapping(value = "/{placeId}/strategies", produces = "application/json")
    public Object selectStrategies(StrategyQuery qo) {
        qo.setPageSize(4);
        PageInfo<Strategy> all = strategyService.query(qo);
        return all;
    }
}
